package Future_FutureTask_13;
import java.util.*;
import java.util.concurrent.*;
public class 批量任务处理_invokeAll示例 {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        final int TASK_COUNT = 15;
        List<Callable<Integer>> tasks = new ArrayList<>(TASK_COUNT);

        // 准备任务列表
        for (int i = 0; i < TASK_COUNT; i++) {
            final int taskId = i;
            tasks.add(new Callable<Integer>() {
                public Integer call() throws Exception {
                    int sleepTime = 500 + (int)(Math.random() * 1000);
                    Thread.sleep(sleepTime);
                    return sleepTime;
                }
            });
        }

        try {
            // 提交所有任务并等待完成
            List<Future<Integer>> futures = executor.invokeAll(tasks);

            // 处理结果
            int totalTime = 0;
            for (int i = 0; i < futures.size(); i++) {
                try {
                    int time = futures.get(i).get();
                    totalTime += time;
                    System.out.println("任务 " + i + " 耗时: " + time + "ms");
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("所有任务总耗时: " + totalTime + "ms");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        executor.shutdown();
    }
}